package com.qf.usermanageradmin.interceptor;

import com.qf.usermanageradmin.entity.User;
import com.qf.usermanageradmin.utils.AccessDeniedException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

// handler就是目标controller中的方法对象
@Component
public class AuthInterceptor implements HandlerInterceptor {

    /**
     * 返回true是放行,false是不放行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求对象中获取session
        HttpSession session = request.getSession();
        // 从session中获取存储的数据
        User user = (User) session.getAttribute("user");
        // 判断
        if (user == null) {
            throw new AccessDeniedException("没有权限,拒绝访问!");
        }
        return true;
    }
}
